package com.youmingxing.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.tencent.upload.task.ITask;
import com.tencent.upload.task.IUploadTaskListener;
import com.tencent.upload.task.data.FileInfo;
import com.youmingxing.R;
import com.youmingxing.activity.selfInfo.EditTextActivity;
import com.youmingxing.bean.User;
import com.youmingxing.bean.Web;
import com.youmingxing.network.AllStarApi;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.network.SelfInfoApi;
import com.youmingxing.network.TXYUploadManager;
import com.youmingxing.utils.TimeUtils;
import com.youmingxing.utils.Util;
import com.youmingxing.view.MyDatePickerDialog;

import org.json.JSONObject;

import java.io.File;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

/**
 * @author evilyin(ChenZhixi)
 * @since 2015-9-12
 */

public class InfoConfirmActivity extends BaseActivity {

    private String[] confirmList = {"头像", "艺名", "性别", "生日", "联系手机", "联系邮箱"};
    private int[] confirmDesc = {R.string.confirm_avatar_requirement, R.string.set_nickname, R.string.set_gender, R.string.birthday,
            R.string.secret, R.string.secret};
    private String[] resultList = new String[6];

    private LinearLayout confirmLayout;
    private Button confirmButton;
    private TextView confirmText1;
    private TextView confirmtext2;

    private static final int HEAD_IMG = 1;
    private static final int EDIT_TEXT = 2;
    private int movieId;
    private int cateId;
    private String auditionName;
    final int CROP_HEAD_IMG = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseSetContentView(R.layout.activity_info_confirm);
        setTopbarName("报名确认");
        Bundle bundle = getIntent().getExtras();
        movieId = bundle.getInt("movie_id");
        cateId = bundle.getInt("cate_id");
        auditionName = bundle.getString("audition_name", "");
        confirmLayout = (LinearLayout) findViewById(R.id.confirm_main_area);
        confirmButton = (Button) findViewById(R.id.confirm_button);
        confirmText1 = (TextView) findViewById(R.id.confirm_validate);
        confirmtext2 = (TextView) findViewById(R.id.confirm_validate2);

        loadData();

        findViewById(R.id.agree_audition).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(InfoConfirmActivity.this, WebViewActivity.class);
                intent.putExtra("web_page", Web.audition);
                startActivity(intent);
            }
        });
    }

    private void loadData() {
        showDialog("正在验证报名资格");
        confirmLayout.removeAllViews();
        AllStarApi.checkUserInfo(jsonHandler);
    }

    BaseJsonHandler jsonHandler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
            JSONObject data = response.optJSONObject("data");
            resultList[0] = data.optString("headimg");
            resultList[1] = data.optString("nickname");
            switch (data.optInt("gender")) {
                case 1:
                    resultList[2] = "男";
                    break;
                case 2:
                    resultList[2] = "女";
                    break;
                default:
                    resultList[2] = "未知";
                    break;
            }
            resultList[3] = data.optString("birthday");
            resultList[4] = data.optString("link_mobile");
            resultList[5] = data.optString("link_email");
            boolean completed = true;

            for (int i = 0; i < confirmList.length; i++) {
                View view = View.inflate(InfoConfirmActivity.this, R.layout.item_confirm, null);
                ((TextView) view.findViewById(R.id.confirm_title)).setText(confirmList[i]);
                TextView result = (TextView) view.findViewById(R.id.confirm_result);
                TextView modify = (TextView) view.findViewById(R.id.confirm_modify);
                ImageView confirmImage = (ImageView) view.findViewById(R.id.confirm_result_image);
                ImageView headImage = (ImageView) view.findViewById(R.id.confirm_head_image);

                if (i == 0) {
                    modify.setVisibility(View.GONE);
                    headImage.setVisibility(View.VISIBLE);
                    result.setText(confirmDesc[0]);
                    if (!resultList[0].equals("")) {
                        Glide.with(InfoConfirmActivity.this).load(resultList[0])
                                .placeholder(R.drawable.default_avatar).error(R.drawable.default_avatar)
                                .bitmapTransform(new CropCircleTransformation(InfoConfirmActivity
                                        .this)).crossFade().into
                                (headImage);
                        confirmImage.setImageResource(R.mipmap.ok);
                    } else {
                        confirmImage.setImageResource(R.mipmap.error);
                        completed = false;
                    }
                } else {
                    modify.setVisibility(View.VISIBLE);
                    headImage.setVisibility(View.GONE);
                    if (!resultList[i].equals("")) {
                        modify.setText(R.string.modify);
                        result.setText(resultList[i]);
                        confirmImage.setImageResource(R.mipmap.ok);
                    } else {
                        modify.setText("设置");
                        result.setText(confirmDesc[i]);
                        confirmImage.setImageResource(R.mipmap.error);
                        completed = false;
                    }
                }
                view.setOnClickListener(new ConfirmClickListener(i));
                confirmLayout.addView(view);
            }
            if (completed) {
                confirmText1.setText(R.string.confirm_info);
                confirmtext2.setText(R.string.confirm_info2);
                confirmButton.setClickable(true);
                confirmButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(InfoConfirmActivity.this);
                        builder.setTitle("您确定要报名" + auditionName + "活动?").setMessage(R.string
                                .sign_up_audition_message)
                                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        showDialog("正在提交");
                                        AllStarApi.applyAudition(movieId, cateId, applyHandler);
                                    }
                                }).setNegativeButton("否", null).show();
                    }
                });

            } else {
                confirmText1.setText(R.string.confirm_failed);
                confirmtext2.setText(R.string.confirm_failed2);
            }
        }
    };

    private BaseJsonHandler applyHandler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
            if (response.optInt("status") == 200) {
                showToast("报名成功!");
                finish();
            } else {
                showToast(response.optString("statusText"));
            }
        }
    };

    private class ConfirmClickListener implements View.OnClickListener {

        int position;

        public ConfirmClickListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(InfoConfirmActivity.this, EditTextActivity.class);
            switch (position) {
                case 0:
                    PhotoPickerIntent intentPP = new PhotoPickerIntent(InfoConfirmActivity.this);
                    intentPP.setPhotoCount(1);
                    intentPP.setShowCamera(true);
                    intentPP.setShowGif(false);
                    startActivityForResult(intentPP, HEAD_IMG);
                    break;
                case 1:
                    intent.putExtra("option", User.Info.nickname.ordinal());
                    intent.putExtra("text", resultList[position]);
                    startActivityForResult(intent, EDIT_TEXT);
                    break;
                case 4:
                    intent.putExtra("option", User.Info.link_mobile.ordinal());
                    intent.putExtra("text", resultList[position]);
                    startActivityForResult(intent, EDIT_TEXT);
                    break;
                case 5:
                    intent.putExtra("option", User.Info.link_email.ordinal());
                    intent.putExtra("text", resultList[position]);
                    startActivityForResult(intent, EDIT_TEXT);
                    break;
                case 2:
                    AlertDialog.Builder builder = new AlertDialog.Builder(InfoConfirmActivity.this);
                    final String[] sex = {"男", "女"};
                    builder.setItems(sex, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            SelfInfoApi.modifyUserProfile("gender", which + 1 + "", modifyHandler);
                        }
                    });
                    builder.show();
                    break;
                case 3:
                    int[] defaultDate = TimeUtils.parseBirthday(resultList[3]);
                    MyDatePickerDialog dpDialog = new MyDatePickerDialog(InfoConfirmActivity.this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            String date = year + "." + (monthOfYear + 1) + "." + dayOfMonth;
                            SelfInfoApi.modifyUserProfile("birthday", date, modifyHandler);
                        }
                    }, defaultDate[0], defaultDate[1] - 1, defaultDate[2]);
                    dpDialog.show();
                    break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case HEAD_IMG:
                    String photoPath = data.getStringArrayListExtra(PhotoPickerActivity
                            .KEY_SELECTED_PHOTOS).get(0);
                    File file = new File(photoPath);
                    Uri mUri = Uri.fromFile(file);
                    if (null == mUri) return;
                    Intent intent = new Intent();
                    intent.setAction("com.android.camera.action.CROP");
                    intent.setDataAndType(mUri, "image/*");// mUri是已经选择的图片Uri
                    intent.putExtra("crop", "true");
                    intent.putExtra("aspectX", 1);// 裁剪框比例
                    intent.putExtra("aspectY", 1);
                    intent.putExtra("outputX", 300);// 输出图片大小
                    intent.putExtra("outputY", 300);
                    intent.putExtra("return-data", true);
                    InfoConfirmActivity.this.startActivityForResult(intent, CROP_HEAD_IMG);
                    break;
                case CROP_HEAD_IMG:
                    // 拿到剪切数据
                    Bitmap bmap = data.getParcelableExtra("data");
                    byte[] img = Util.Bitmap2Bytes(Util.compressImage(bmap));
                    bmap.recycle();
                    showDialog("图片上传中");
                    TXYUploadManager.uploadPhoto(img, new
                            IUploadTaskListener() {
                                @Override
                                public void onUploadSucceed(FileInfo fileInfo) {
                                    SelfInfoApi.modifyUserProfile("headimg", fileInfo.url, modifyHandler);
                                    Toast.makeText(InfoConfirmActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onUploadFailed(int i, String s) {
                                    hideDialog();
                                    Toast.makeText(InfoConfirmActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onUploadProgress(long l, long l1) {

                                }

                                @Override
                                public void onUploadStateChange(ITask.TaskState taskState) {

                                }
                            });
                    break;
                case EDIT_TEXT:
                    loadData();
                    break;

            }

        }
    }

    private BaseJsonHandler modifyHandler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
            showToast("修改成功");
            loadData();
        }
    };

}
